<template>
  <div class="hot-money-list">
    <!-- 页面级Loading -->
    <div v-if="pageLoading" class="page-loading">
      <div v-loading="true" element-loading-text="正在加载游资列表..." element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)" class="loading-overlay">
        <div style="height: 100vh;"></div>
      </div>
    </div>

    <!-- 错误信息显示 -->
    <div v-else-if="pageError" class="page-error">
      <el-result icon="error" :title="errorTitle" :sub-title="errorMessage">
        <template #extra>
          <el-button type="primary" @click="retryLoad">重新加载</el-button>
        </template>
      </el-result>
    </div>

    <!-- 正常内容 -->
    <div v-else>
      <div class="page-header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }"><el-icon>
              <House />
            </el-icon></el-breadcrumb-item>
          <el-breadcrumb-item>游资列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="content-area">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门游资</span>
            </div>
          </template>

          <el-table :data="hotMoneyList" stripe style="width: 100%">
            <el-table-column prop="hotMoneyName" label="游资名称" width="220">
              <template #default="scope">
                <span class="investor-name">{{ scope.row.hotMoneyName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="heldStockCount" label="持仓票数" width="120">
              <template #default="scope">
                <span>{{ scope.row.heldStockCount }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="netBuyAmount" label="持仓总额" width="200">
              <template #default="scope">
                <span :class="{
                  'profit-positive': scope.row.netBuyAmount > 0,
                  'profit-negative': scope.row.netBuyAmount < 0
                }">
                  {{ formatAmountWan(scope.row.netBuyAmount, true) }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="winPrice" label="盈利金额" width="200">
              <template #default="scope">
                <span :class="{
                  'profit-positive': scope.row.winPrice > 0,
                  'profit-negative': scope.row.winPrice < 0
                }">{{ formatAmountWan(scope.row.winPrice) }}</span>
              </template>
            </el-table-column>


            <el-table-column prop="winRate" label="胜率" width="150">
              <template #default="scope">
                <span class="win-rate">{{ formatRate(scope.row.winRate) }}</span>
              </template>
            </el-table-column>

            
            
            
            <el-table-column label="买卖情况" >
              <template #default="scope">
                <TradeProgress
                  :buy-amount="scope.row.buyAmount"
                  :sell-amount="scope.row.sellAmount"
                  :net-buy-amount="scope.row.netBuyAmount"
                  :tooltip="true"
                  :show-labels="true"
                />
              </template>
            </el-table-column>




            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button type="primary" size="small" @click="viewDetails(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination background layout="total, prev, pager, next, jumper" :total="pagination.totalCount"
              :page-size="pagination.pageSize" :current-page="pagination.pageIndex"
              @current-change="handlePageChange" />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { House } from '@element-plus/icons-vue'
import { hotMoneyAPI } from '@/utils/api'
import TradeProgress from '@/components/TradeProgress.vue'

const router = useRouter()

// 页面状态管理
const pageLoading = ref(false)
const pageError = ref(false)
const errorMessage = ref('')
const errorTitle = ref('请求失败')

// 列表与分页
const hotMoneyList = ref([])
const pagination = ref({
  pageIndex: 1,
  pageSize: 20,
  totalCount: 0,
  totalPages: 0,
  hasPrevPages: false,
  hasNextPages: false
})

const formatRate = (val) => {
  if (val === null || val === undefined || val === '') return '-'
  // 若后台已返回百分号字符串则直接显示，否则按百分比格式化
  if (typeof val === 'string') return val
  const num = Number(val)
  if (isNaN(num)) return '-'
  // 假设后台返回0-100区间，如为0-1可改为(num*100)
  return `${num}%`
}

// 金额格式化：转为“万”，保留1位小数，可选显示正负号
const formatAmountWan = (val, withSign = false) => {
  if (val === null || val === undefined || isNaN(Number(val))) return '-'
  const num = Number(val) / 10000
  if (withSign) {
    const sign = num > 0 ? '+' : (num < 0 ? '-' : '')
    const absStr = Math.abs(num).toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
    return `${sign}${absStr}万`
  }
  return `${num.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })}万`
}

// 获取列表
const fetchHotMoneyList = async () => {
  pageLoading.value = true
  pageError.value = false

  try {
    const res = await hotMoneyAPI.getHotMoneyList(pagination.value.pageIndex)

    if (res && res.succeeded && res.data) {
      const data = res.data
      hotMoneyList.value = data.items || []
      pagination.value = {
        pageIndex: (data.pageIndex ?? 1),
        pageSize: (data.pageSize ?? pagination.value.pageSize),
        totalCount: (data.totalCount ?? 0),
        totalPages: (data.totalPages ?? 0),
        hasPrevPages: !!data.hasPrevPages,
        hasNextPages: !!data.hasNextPages
      }
      pageLoading.value = false
    } else {
      pageLoading.value = false
      pageError.value = true
      errorTitle.value = '请求失败'
      errorMessage.value = res?.errors || '获取游资列表失败'
    }
  } catch (error) {
    pageLoading.value = false
    pageError.value = true
    errorTitle.value = '请求失败'
    errorMessage.value = error?.message || '获取游资列表失败'
  }
}

// 翻页
const handlePageChange = (page) => {
  pagination.value.pageIndex = page
  fetchHotMoneyList()
}

// 查看详情
const viewDetails = (row) => {
  const id = row.hotMoneyId ?? row.id
  if (!id) {
    ElMessage.error('缺少游资ID')
    return
  }
  router.push({
    name: 'hotMoneyDetail',
    params: { id }
  })
}

const retryLoad = () => {
  fetchHotMoneyList()
}

onMounted(() => {
  fetchHotMoneyList()
})
</script>

<style scoped>
.card-header {
  font-family: HarmonyOS Sans SC;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
  display: flex;
  align-items: center;
  letter-spacing: normal;
  color: #1D2129;
}

.hot-money-list {
  padding: 24px;
}

/* 页面级Loading样式 */
.page-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

.loading-overlay {
  width: 100%;
  height: 100%;
}

/* 错误页面样式 */
.page-error {
  padding: 40px 20px;
}

.page-header {
  margin-bottom: 24px;
}

.content-area {
  min-height: 400px;
}

.investor-name {
  font-weight: 500;
  color: #303133;
}

.profit-positive {
  color: #EA0000;
  font-weight: 600;
}

.profit-negative {
  color: #529B2E;
  font-weight: 600;
}


.win-rate {
  color: #409EFF;
  font-weight: 500;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.el-table) {
  font-family: 'Inter', 'HarmonyOS Sans SC', sans-serif;
}

:deep(.el-table th) {
  background-color: #F5F7FA;
  color: #909399;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #F5F7FA;
}


/* 买卖情况进度条样式（样式已在 TradeProgress 组件内定义，此处移除） */

</style>